package band.wukong.practice.netty.sample.tcpsuite;

import band.wukong.practice.netty.Env;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Desc:
 * author: wukonggg@139.com
 */
public class TcpServer {

    private static final Logger logger;
    static {
        Env.assemblingLog4j2ConfFile();
        logger = LogManager.getLogger();
    }

    private String host;
    private int port;

    public TcpServer(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void bind() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new TcpServerChannelInitializer())
                .option(ChannelOption.SO_BACKLOG, 1024);

        try {
            ChannelFuture f = b.bind(host, port).sync();
            logger.info("Server started, listening on port {}. ", port);

            f.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            logger.error(e.getMessage());
            e.printStackTrace();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            logger.info("Server shutdown.");
        }

    }

    public static void main(String[] args) {
        new TcpServer(Env.HOST, Env.PORT).bind();
    }
}
